package u1;

import static u1.Util.trace;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.stream.XMLStreamException;

import org.xml.sax.SAXException;

/**
 * Read Wiki dump and write a subset of the pages (chosen by the subclass, which
 * overrides the pull method) to the given output stream.
 */
@SuppressWarnings("serial")
public abstract class PagePuller extends PageReader {
  private Map<String, String> numberAttrib = new HashMap<String, String>() {
    {
      put("number", "");
    }
  };
  private int count;
  private int pageNumber = 0;
  private PageWriter writer;

  public PagePuller(OutputStream os, String rootName,
      Map<String, String> rootAttrib) throws SAXException, XMLStreamException {
    super();
    writer = new PageWriter(os, rootName, rootAttrib);
  }

  @Override
  public void parse(InputStream is) throws IOException, SAXException {
    // TODO Auto-generated method stub
    super.parse(is);
    
    try {
      writer.close();
    } catch (XMLStreamException e) {
      e.printStackTrace();
    }
    trace("Found %d articles.", count);
  }

  /**
   * Override to decide whether to pull a particular page.
   * 
   * @param title
   *          not null
   * @param text
   *          not null
   * @return
   */
  protected abstract boolean pull(String title, String text);

  @Override
  protected void readPage(String title, String text) {
    if (pull(title, text)) {
      numberAttrib.put("number", String.valueOf(pageNumber));
      writer.writePage(title, text, numberAttrib);
      count++;
    }
    ++pageNumber;
  }

}
/*
* Copyright (c) 2009 John Lees-Miller
* 
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* 
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/

